package com.teach.config.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.teach.AuthUser;
import com.teach.CodeException;
import com.teach.annotation.CheckLogin;
import com.teach.annotation.CheckRole;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <pre>
 * 权限验证拦截器
 * Class: com.teach.config.AuthInterceptor
 * Copyright 2022 jlzhou.top Inc. All rights reserved.
 * Warning: this content is only for internal circulation of the company.
 *          It is forbidden to divulge it or use it for other commercial purposes.
 * </pre>
 * 
 * @author J.L.Zhou
 * @since 2022年10月22日 下午2:09:06
 * @version 1.0
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.trace("handler:{},{}", handler.getClass(), handler);
    if (handler instanceof HandlerMethod) {
      HandlerMethod handlerMethod = (HandlerMethod) handler;
      CheckLogin checkLogin = handlerMethod.getMethodAnnotation(CheckLogin.class);
      CheckRole checkRole = handlerMethod.getMethodAnnotation(CheckRole.class);
      log.trace("checkLogin:{}", checkLogin);
      log.trace("checkRole:{}", checkRole);
      if (checkLogin != null || checkRole != null) {
        if(AuthUser.get()==null){
          throw new CodeException(1, "未登录");
        }
      }
      if (checkRole != null) {
        if(Arrays.asList(checkRole.value()).contains(AuthUser.get().getRoleId())){
          throw new CodeException(2, "无权操作");
        }
      }


    }
    return true;
  }

}
